<!--  -->
<template>
  <div class="purchase-goods">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select 
            v-model="searchForm.supplierId" 
            placeholder="请选择供应商"
            clearable
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row :gutter="20">
      <!-- 商品列表 -->
      <el-col :span="16">
        <el-card>
          <div slot="header">
            <span>商品列表</span>
          </div>
          <el-table
            v-loading="loading"
            :data="productList"
            border
            stripe
          >
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="imageUrl" label="商品图片" width="100">
              <template slot-scope="scope">
                <el-image
                  :src="scope.row.imageUrl"
                  :preview-src-list="[scope.row.imageUrl]"
                  fit="cover"
                  style="width: 50px; height: 50px"
                >
                  <div slot="error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="supplierName" label="供应商" min-width="120" />
            <el-table-column prop="purchasePrice" label="采购价" width="120">
              <template slot-scope="scope">
                ¥{{ scope.row.purchasePrice }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="addToCart(scope.row)"
                >
                  加入购物车
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination
              :current-page.sync="pageNum"
              :page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 购物车 -->
      <el-col :span="8">
        <el-card class="cart-card">
          <div slot="header">
            <span>采购购物车</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="clearCart"
            >
              清空购物车
            </el-button>
          </div>

          <div v-if="cartList.length === 0" class="empty-cart">
            <i class="el-icon-shopping-cart-2"></i>
            <p>购物车是空的</p>
          </div>

          <div v-else>
            <div 
              v-for="item in cartList" 
              :key="item.productId" 
              class="cart-item"
            >
              <div class="item-info">
                <el-image
                  :src="item.imageUrl"
                  fit="cover"
                  style="width: 40px; height: 40px"
                >
                  <div slot="error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div class="item-detail">
                  <div class="item-name">{{ item.productName }}</div>
                  <div class="item-price">¥{{ item.purchasePrice }}</div>
                </div>
              </div>
              <div class="item-action">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  size="mini"
                  @change="calculateTotal"
                />
                <el-button
                  type="text"
                  class="delete-btn"
                  @click="removeFromCart(item)"
                >
                  删除
                </el-button>
              </div>
            </div>

            <div class="cart-footer">
              <div class="total-info">
                <span>总数量：{{ totalQuantity }}件</span>
                <span>总金额：¥{{ totalAmount }}</span>
              </div>
              <el-button 
                type="primary" 
                :disabled="cartList.length === 0"
                @click="submitOrder"
              >
                提交采购订单
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 确认订单对话框 -->
    <el-dialog
      title="确认采购订单"
      :visible.sync="dialogVisible"
      width="500px"
    >
      <div class="order-confirm">
        <div class="order-items">
          <div v-for="item in cartList" :key="item.productId" class="order-item">
            <span>{{ item.productName }}</span>
            <span>{{ item.quantity }}件</span>
            <span>¥{{ (item.purchasePrice * item.quantity).toFixed(2) }}</span>
          </div>
        </div>
        <div class="order-total">
          <div>总计：¥{{ totalAmount }}</div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmOrder" :loading="submitting">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getProductList } from '@/api/products'
import { getSuppliers } from '@/api/suppliers'
import { createPurchaseOrder } from '@/api/purchaseOrders'

export default {
  name: 'PurchaseGoods',
  data() {
    return {
      loading: false,
      submitting: false,
      dialogVisible: false,
      searchForm: {
        productName: '',
        supplierId: ''
      },
      productList: [],
      cartList: [],
      supplierOptions: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      totalQuantity: 0,
      totalAmount: '0.00'
    }
  },
  created() {
    this.getList()
    this.getSuppliers()
    // 从localStorage恢复购物车数据
    const cartData = localStorage.getItem('purchaseCart')
    if (cartData) {
      this.cartList = JSON.parse(cartData)
      this.calculateTotal()
    }
  },
  methods: {
    async getList() {
      this.loading = true
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        const res = await getProductList(params)
        if (res.code === 200) {
          this.productList = res.data.list
          this.total = res.data.total
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败')
      } finally {
        this.loading = false
      }
    },
    async getSuppliers() {
      try {
        const res = await getSuppliers()
        if (res.code === 200) {
          this.supplierOptions = res.data.list
        }
      } catch (error) {
        console.error('获取供应商列表失败:', error)
        this.$message.error('获取供应商列表失败')
      }
    },
    handleSearch() {
      this.pageNum = 1
      this.getList()
    },
    resetSearch() {
      this.searchForm = {
        productName: '',
        supplierId: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getList()
    },
    addToCart(product) {
      const existItem = this.cartList.find(item => item.productId === product.productId)
      if (existItem) {
        existItem.quantity += 1
      } else {
        this.cartList.push({
          ...product,
          quantity: 1
        })
      }
      this.calculateTotal()
      this.saveCartToStorage()
      this.$message.success('已加入购物车')
    },
    removeFromCart(item) {
      const index = this.cartList.findIndex(cartItem => cartItem.productId === item.productId)
      if (index > -1) {
        this.cartList.splice(index, 1)
        this.calculateTotal()
        this.saveCartToStorage()
      }
    },
    clearCart() {
      this.cartList = []
      this.calculateTotal()
      this.saveCartToStorage()
    },
    calculateTotal() {
      this.totalQuantity = this.cartList.reduce((sum, item) => sum + item.quantity, 0)
      this.totalAmount = this.cartList.reduce((sum, item) => {
        return sum + item.purchasePrice * item.quantity
      }, 0).toFixed(2)
    },
    saveCartToStorage() {
      localStorage.setItem('purchaseCart', JSON.stringify(this.cartList))
    },
    submitOrder() {
      if (this.cartList.length === 0) {
        this.$message.warning('购物车是空的')
        return
      }
      this.dialogVisible = true
    },
    async confirmOrder() {
      this.submitting = true
      try {
        // 构建订单项数据
        const orderItems = this.cartList.map(item => ({
          productId: item.productId,
          quantity: item.quantity,
          price: item.purchasePrice,
          supplierId: item.supplierId
        }))

        const res = await createPurchaseOrder(orderItems)  // 直接传递订单项数组
        
        if (res.code === 200) {
          this.$message.success('采购订单提交成功')
          this.clearCart()
          this.dialogVisible = false
          // 跳转到订单列表页面
          this.$router.push('/purchase/orders')
        } else {
          this.$message.error(res.msg || '提交失败')
        }
      } catch (error) {
        console.error('提交采购订单失败:', error)
        this.$message.error('提交采购订单失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.purchase-goods {
  padding: 20px;

  .search-section {
    background: #fff;
    padding: 18px 20px;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  }

  .pagination-section {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .cart-card {
    position: sticky;
    top: 20px;

    .empty-cart {
      text-align: center;
      padding: 40px 0;
      color: #909399;

      i {
        font-size: 48px;
        margin-bottom: 10px;
      }
    }

    .cart-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #EBEEF5;

      .item-info {
        display: flex;
        align-items: center;
        flex: 1;

        .item-detail {
          margin-left: 10px;

          .item-name {
            font-size: 14px;
            margin-bottom: 5px;
          }

          .item-price {
            color: #F56C6C;
            font-size: 13px;
          }
        }
      }

      .item-action {
        display: flex;
        align-items: center;

        .delete-btn {
          margin-left: 10px;
          color: #F56C6C;
        }
      }
    }

    .cart-footer {
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #EBEEF5;

      .total-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
        font-size: 14px;
        color: #606266;
      }
    }
  }
}

.order-confirm {
  .order-items {
    max-height: 300px;
    overflow-y: auto;

    .order-item {
      display: flex;
      justify-content: space-between;
      padding: 10px 0;
      border-bottom: 1px solid #EBEEF5;

      &:last-child {
        border-bottom: none;
      }
    }
  }

  .order-total {
    margin-top: 20px;
    text-align: right;
    font-size: 16px;
    font-weight: bold;
    color: #F56C6C;
  }
}
</style>